const QuestionType = require('../models/questionType');
const KPoint = require('../models/kPoint');
const Question = require('../models/question');
const Sequelize = require('sequelize')

//题型与题目 一对多关系
QuestionType.hasMany(Question,{foreignKey:'type_id',sourceKey:'type_id'});
Question.belongsTo(QuestionType,{foreignKey:'type_id',targetKey:'type_id'});
//知识点与题目 一对多关系
KPoint.hasMany(Question,{foreignKey:'kp_id',sourceKey:'kp_id'});
Question.belongsTo(KPoint,{foreignKey:'kp_id',targetKey:'kp_id'});

class QuestionsCtl{
  async find(ctx){
    const currentPage = ctx.request.query.currentPage
    const {count,rows} = await Question.findAndCountAll({
      include:[{
        model:QuestionType,
        attributes:[],
        required: true,
        
      },{
        model:KPoint,
        attributes:[],
        required: true,
      }],
      attributes:
        ['question_id','question','answer','type_id',[Sequelize.col('QuestionType.type_name'), 'type_name'],'kp_id',[Sequelize.col('KPoint.kp_name'), 'kp_name']],
      limit:  10,
      offset: (currentPage - 1) * 10,
      order:[['question_id','asc']]
    })
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  async findAll(ctx){
    const {count,rows} = await Question.findAndCountAll({
      include:[{
        model:QuestionType,
        attributes:[],
        required: true,
        
      },{
        model:KPoint,
        attributes:[],
        required: true,
      }],
      attributes:
        ['question_id','question','answer','type_id',[Sequelize.col('QuestionType.type_name'), 'type_name'],'kp_id',[Sequelize.col('KPoint.kp_name'), 'kp_name']],
    })
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  async create(ctx){
    const {type_id,kp_id,question,answer} = ctx.request.body;
    const newQuestion = await Question.create({
      type_id,
      kp_id,
      question,
      answer,
    });
    ctx.body = newQuestion;
  }
  async update(ctx){
    const _question = await Question.findOne({
      where:{
        question_id:ctx.params.id
      }
    })
    if(!_question){ctx.throw(404,'当前题目不存在')}
    const {type_id,kp_id,question,answer} = ctx.request.body;
    await _question.update({
      type_id,
      kp_id,
      question,
      answer
    },{
      where:{
        question_id:ctx.params.id
      }
    })
    ctx.body = _question
  }
  async delete(ctx){
    const _question = await Question.findOne({
      where:{
        question_id:ctx.params.id
      }
    })
    if(!_question){ctx.throw(404,'当前题目不存在')}
    await _question.destroy();
    ctx.status = 204
  }
}
module.exports = new QuestionsCtl();